package com.test.comlection;

public class HashTable<E> {

    private final int TABLE_SIZE = 10;
    private final Node<E>[] TABLE = new Node[TABLE_SIZE];


    public HashTable() {
        for (int i = 0; i < TABLE_SIZE; i++) {
            TABLE[i] = new Node<>(null);
        }
    }
    //插入
    public void insert(E element) {
        int index = hash(element);
        Node<E> prev = TABLE[index];
       while (prev.next != null) {
           prev = prev.next;
       }
       prev.next = new Node<>(element);
    }

    //查找
    public boolean contains(E element){
        int index = hash(element);
        Node<E> node = TABLE[index].next;
        while(node != null){
            if(node.element == element)
                return true;
            node = node.next;
        }
        return false;
    }

    private int hash(E obj){    //哈希函数，计算出存放的位置
        int hashCode = obj.hashCode();//每一个对象都有一个独一无二的哈希值，可以通过hashCode方法得到（只有极小的概率会出现相同的情况）
        return hashCode % TABLE_SIZE;
    }

    @Override
    public String toString(){
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < TABLE_SIZE; i++) {
            Node<E> head = TABLE[i].next;
            while(head != null){
                builder.append(head.element).append("->");
                head = head.next;
            }
            builder.append("\n");
        }
        return builder.toString();
    }
    private static class Node<E>{

        private final E element;
        private Node<E> next;

        public Node(E element){
            this.element = element;
        }
    }
}
